package com.study.kafka.custom.serialization;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
import org.apache.kafka.common.serialization.Serializer;

import java.util.Map;

/**
 * 自定义序列化，使用protostuff实现
 *
 * @author: stephen.shen
 * @create: 2019-06-18 11:04
 */
public class DemoSerializer implements Serializer<Person> {

    /**
     * 配置当前类
     * 创建 KafkaProducer 实例的时候调用
     *
     * @param configs
     * @param isKey
     */
    @Override
    public void configure(Map<String, ?> configs, boolean isKey) {

    }

    /**
     * 执行序列化操作
     *
     * @param topic
     * @param data
     * @return
     */
    @Override
    public byte[] serialize(String topic, Person data) {
        if (data == null) {
            return null;
        }
        Schema schema = RuntimeSchema.getSchema(data.getClass());
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        byte[] protostuff = null;
        try {
            protostuff = ProtostuffIOUtil.toByteArray(data, schema, buffer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            buffer.clear();
        }
        return protostuff;
    }

    /**
     * 关闭当前的序列化器
     * 可能会多次调用
     */
    @Override
    public void close() {

    }
}
